import { getProgramOptions } from '@/services/api';
import { useRequest } from '@umijs/max';
import type { TransferProps } from 'antd';
import { Modal, Transfer } from 'antd';
import { isEqual } from 'lodash';
import React, { useEffect, useState } from 'react';

interface RecordType {
  key: string;
  title: string;
  description: string;
  chosen: boolean;
}

const CommonTransfer: React.FC<any> = ({ open, onClose, onOk, initValues }) => {
  const [targetKeys, setTargetKeys] = useState<any>(initValues);

  useEffect(() => {
    setTargetKeys(initValues);
  }, [initValues]);

  // 查询所有商户
  const { data: merchantList } = useRequest(async () => {
    return await getProgramOptions();
  });

  const filterOption = (inputValue: string, option: RecordType) =>
    option.label.indexOf(inputValue) > -1;

  const handleChange: TransferProps['onChange'] = (newTargetKeys) => {
    setTargetKeys(newTargetKeys);
  };

  const handleSearch: TransferProps['onSearch'] = (dir, value) => {
    console.log('search:', dir, value);
  };

  return (
    <Modal
      open={open}
      onCancel={onClose}
      width={800}
      closeIcon={false}
      onOk={() => {
        onOk?.(targetKeys);
      }}
    >
      <Transfer
        listStyle={{
          width: 800,
          height: 600,
        }}
        titles={['全部', '已选择']}
        dataSource={merchantList}
        showSearch
        filterOption={filterOption}
        targetKeys={targetKeys}
        onChange={handleChange}
        onSearch={handleSearch}
        render={(item) => {
          return <>{item.label} </>;
        }}
        rowKey={(record) => record.value}
      />
    </Modal>
  );
};

export default React.memo(CommonTransfer, (prev, next) => isEqual(prev, next));
